#!/usr/bin/env python3
# coding: utf-8
# Copyright 2024 Huawei Technologies Co., Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
# ===========================================================================
import os
import json
import platform

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils import common_info, common_utils, venv_installer
from ansible.module_utils.common_info import DeployStatus


class OpenGaussInstaller:
    def __init__(self):
        self.module = AnsibleModule(
            argument_spec=dict(
                tags=dict(type="list", required=True),
                resources_dir=dict(type="str", required=True),
            )
        )
        self.run_tags = self.module.params["tags"]
        self.resources_dir = os.path.expanduser(self.module.params["resources_dir"])
        self.messages = []

    def _module_failed(self):
        return self.module.fail_json(msg="\n".join(self.messages), rc=1, changed=False)

    def _module_success(self):
        return self.module.exit_json(msg="Install opengauss success.", rc=0, changed=True)

    def _find_opengauss_pkg(self, pattern):
        pkgs, msgs = common_utils.find_files(os.path.join(self.resources_dir, "openGauss*"), pattern)
        self.messages.extend(msgs)
        if not pkgs:
            if "auto" in self.run_tags:
                self.module.exit_json(std_out="can not find opengauss package, opengauss install skipped", rc=0,
                                      result={DeployStatus.DEPLOY_STATUS: DeployStatus.SKIP},
                                      changed=False)
            else:
                self.messages.append("can not find opengauss package.")
                self._module_failed()

        return pkgs[0]
    
    def _get_config(self):
        config_path = self._find_opengauss_pkg("opengauss_config.json")
        with open(config_path, 'r') as f:
            self.config = json.load(f)

    def load_opengauss_image(self):
        opengauss_pattern = "openGauss*.tar"
        opengauss_path = self._find_opengauss_pkg(opengauss_pattern)
        if not self.module.get_bin_path("docker"):
            self.module.fail_json("Docker not installed, please install docker first.")
        rc, out, err = self.module.run_command(["docker", "load", "-i", opengauss_path])
        if rc != 0:
            self.module.fail_json(
                'Failed to loading Docker image from {}, error:{}'.format(opengauss_path, err))
        self.messages.append("Loading Docker image from {} successfully.".format(opengauss_path))
        for line in out.splitlines():
            if 'Loaded image:' in line:
                return line.split()[-1]
        return self.module.fail_json('opengauss image loaded, but can not get image name.')

    def run_opengauss_container(self):
        image_name = self.load_opengauss_image()
        data_path = "{}:/var/lib/opengauss".format(self.config.get("data_path", ""))
        command = [
            "docker", "run", "--name", "opengauss", "-d", "--privileged=true",
            "-p", "{}:5432".format(self.config.get("port", 8888)),
            "-e", "GS_PASSWORD={}".format(self.config.get("password", "")),
            image_name]
        rc, _, err = self.module.run_command(command)
        if rc != 0:
            self.module.fail_json(msg='Failed to run opengauss, error:{}'.format(err))
        self.messages.append("Docker run opengauss successfully.")

    def run(self):
        try:
            self._get_config()
            self.run_opengauss_container()
        except Exception as e:
            self.messages.append(str(e))
            self._module_failed()
        self._module_success()


def main():
    OpenGaussInstaller().run()


if __name__ == "__main__":
    main()
